﻿using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using SocketIO;


public class Main: BaseController  {
	public static String MUSIC = "music";
	public static String EFFECT = "effect";
	public static string session = null;
	public static string notice = null;
	public static Main Instance = new Main();
	public static User user = new User ();
	public static Room room = null;
	protected static SocketIOComponent socket = null;
	public UISprite errorSprite;
	public static AsyncImageDownload ImageDownload;
	public static List<JSONObject> goods = new List<JSONObject>();
	public static List<JSONObject> pointGoods = new List<JSONObject>();
	private static string ip = null;
	public static bool loginSuccess = false;
	//public void Awake()

	//{

	//    DontDestroyOnLoad(this.gameObject);

	//}

	public void init(){
		AppController.Init();

		InitSocketConfig ();
		ImageDownload = GameObject.Find ("ImageDownLoad").GetComponent<AsyncImageDownload> ();

		//禁止卸载

		DontDestroyOnLoad(ImageDownload);


		BaseCompent.init ();
		AsyncImageDownload.CreateSingleton ();
		if(Main.session == null)
			Main.session = PlayerPrefs.GetString ("SESSION");

		Debug.Log ("取得session：" + session);

		//初始化音效系统

		if (PlayerPrefs.GetInt (Main.MUSIC) == 1) {
			AudioManager.Instance.Play ();
		} else {
			AudioManager.Instance.Pause ();
		}
	}

	public void SocketEmit(string action,JSONObject param){
		Debug.Log (action);
		Debug.Log (param.ToString());
		socket.Emit (action, param);
	}

	static long c_time = 0;
	public static void Update(){
		if(socket != null)
			socket.Update ();

		long currTime = Convert.ToInt64 ((DateTime.UtcNow - new DateTime (1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);


		lock (queues) {
			if (queues.Count > 0) {
				LoginQueue lq = queues [0];
				//发送并且已经返回，移除

				if (lq.isRequest && lq.isReturn) {
					Debug.Log ("移除队列");
					popQueue ();
				} 
				//未发送，发送请求

				else if (!lq.isRequest && socket.sid != null) {
					Debug.Log ("发送队列第一个请求");
					API.Login (lq.session);
					lq.isRequest = true;
				}
			}
		}
	}

	#region 临时代码

	public static string logData = "Log：";
	void OnGUI()
	{
		GUIStyle s = new GUIStyle();
		s.fontSize = 40;
		s.normal.textColor = Color.red;
		GUILayout.Label(logData,s);
	}
	#endregion

	private static Dictionary<string,LoginQueue> temp = new Dictionary<string,LoginQueue>();
	public static List<LoginQueue> queues = new List<LoginQueue> ();
	public static void pushQueue(LoginQueue queue){
		lock (queues) {
			if (queue.session == null || queue.session == "") {
				queue.session = "chovans";
			}
			Debug.Log ("加入队列，session="+queue.session);
			if (temp.ContainsKey (queue.session)) {
				Debug.Log ("包含相同session，return");
				return;
			}

			temp.Add (queue.session, queue);
			queues.Add (queue);	
			Debug.Log ("当前队列size:" + queues.Count);
		}
	}

	//移除队列，清理标志

	public static void popQueue(){
		//		lock (queues) {

		if (queues.Count > 0) {
			LoginQueue lq = queues [0];
			Debug.Log ("移除队列，session="+lq.session);
			temp.Remove (lq.session);
			queues.Remove (lq);
			Debug.Log ("当前队列size:" + queues.Count);
		}
		//		}


	}

	void On(string eventname,Action<SocketIOEvent> callback){
		Action<SocketIOEvent> handle = null;
		handle = (ev) => {
			try {
				callback (ev);
			} catch (Exception ex) {
				//				Debug.Log("！！！！！！！！！！！！error EvenName = "+eventname.ToString());

				//				Debug.Log(ex.StackTrace.ToString());

				//				Debug.Log(ex.Message.ToString());

			} finally {
			}
		};
		socket.On(eventname, handle);
	}
	public void InitSocketConfig(){
		if (socket != null) {
			Debug.Log ("断开Socket");
			socket.Close ();
		}

		socket = new SocketIOComponent();//GameObject.Find("Socket").GetComponent<SocketIOComponent>();

		socket.Awake ();
		socket.Start ();

		Debug.Log ("初始化socket");

		On("open", SocketOpen);
		On("connect", SocketConnect);
		On("error", SocketError);
		On("disconnect", SocketDisconnect);
		On("close", SocketClose);

		SocketOnEmit ();

	}
	//public void Reconnect()

	//{

	//    if (socket != null)

	//    {

	//        Debug.Log("断开Socket");

	//        socket.Close();

	//    }

	//}

	public void SocketOpen(SocketIOEvent e){
		Debug.Log ("Socket IO is Open");
	}

	public static bool isConnected = false;
	public void SocketConnect(SocketIOEvent e){
		Debug.Log ("Sokect Connect");
		logData = "connected";
		isConnected = true;
		if (Main.session != null && Main.session != "") {
			Debug.Log ("创建登录队列");
			//创建队列

			LoginQueue q = new LoginQueue();
			q.time = Convert.ToInt64 ((DateTime.UtcNow - new DateTime (1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
			q.session = Main.session;
			q.isReturn = false;
			q.isRequest = false;
			pushQueue (q);
		}
	}

	public void TestBoop(SocketIOEvent e)
	{
		Debug.Log("[SocketIO] Boop received: " + e.name + " " + e.data);

		if (e.data == null) { return; }

		Debug.Log(
			"#####################################################" +
			"THIS: " + e.data.GetField("this").str +
			"#####################################################"
		);
	}

	public void SocketError(SocketIOEvent e)
	{
		isConnected = false;
		loginSuccess = false;
		logData = "error";
		Debug.Log("[SocketIO] Error received: " + e.name + " " + e.data);
	}

	public void SocketClose(SocketIOEvent e)
	{
		isConnected = false;
		loginSuccess = false;
		//		socket.connected = false;

		//		socket.Close();

		logData += "closed";
		Main.user.id = "";
		Debug.Log("[SocketIO] Close received: " + e.name + " " + e.data);
	}

	public void SocketDisconnect(SocketIOEvent e){
		isConnected = false;
		loginSuccess = false;
		logData += "disconnected";
		Debug.Log ("Sokect Disconnect");
		//		Main.user.id = "";

	}

		
	public void SocketOnEmit(){
		On("player-frame", (SocketIOEvent e) => {
			Debug.Log("player-frame reult:"+e.data);
			user = new User(JSONObject.Create(e.data.ToString()),true);
			if(user.status == USER_STATUS.FREE.GetHashCode()){
				Utils.LoadScene("Home");
			}
			NotificationCenter.Get().DispatchEvent(API.USER_ACTION,e.data.ToString());
		});

		On("try-wx-login", (SocketIOEvent e) => {
			Debug.Log("try-wx-login reult:"+e.data);
		});

		On("room-frame", (SocketIOEvent e) => {
			Debug.Log("room-frame reult:"+e.data);
			//记录状态机
			room = new Room(JSONObject.Create(e.data.ToString()));	
			Utils.checkRoomInfo(e.data.ToString());
			NotificationCenter.Get().DispatchEvent(API.ROOM_ACTION,e.data.ToString());
		});

		On("res-error",(SocketIOEvent e) => {
			Debug.Log("服务端错误提示:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.ERROR_ACTION,e.data.ToString());
		});

		//监听离开房间事件
		On("alert-notice",(SocketIOEvent e) => {
			Debug.Log("退出房间提示:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.ROOM_EXIT_ACTION,e.data.ToString());
		});

		//获取战绩结果
		On("return-user-game-logs",(SocketIOEvent e) => {
			Debug.Log("比赛记录:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.GAME_LOGS,e.data.ToString());
		});

		//获取公告消息
		On("bulletin-json",(SocketIOEvent e) => {
			Debug.Log("消息:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.NOTICE_ACTION,e.data.ToString());
		});

		//接收消息
		On("player-send-msg",(SocketIOEvent e) => {
			Debug.Log("收到文字消息:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.TEXT_MESSAGE,e.data.ToString());
		});

		//房间配置信息
		On("room-setting",(SocketIOEvent e) => {
			Debug.Log("收到房间配置消息:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.ROOM_SETTING,e.data.ToString());
		});

		//通知玩家解散房间
		On("start-disband-room",(SocketIOEvent e) => {
			Debug.Log("通知玩家解散房间:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.DISSOLUTION_ROOM_START,e.data.ToString());
		});

		//解散失败
		On("end-disband-room",(SocketIOEvent e) => {
			Debug.Log("玩家解散房间失败:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.DISSOLUTION_FAIL,e.data.ToString());
		});

		//解散相关消息
		On("alert-notice",(SocketIOEvent e) => {
			Debug.Log("提示消息:"+e.data);
			//			NotificationCenter.Get().DispatchEvent(API.DISSOLUTION_FAIL,e.ToString());
		});

		//接收语音消息
		On("player-send-voice",(SocketIOEvent e) => {
			Debug.Log("接收语音消息:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.VOICE_MESSAGE,e.data.ToString());
		});

		//接收队列列表
		On("queue-size",(SocketIOEvent e) => {
			Debug.Log("人数:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.QUEUE_SIZE,e.data.ToString());
		});

		//接收商品
		On("goods-res",(SocketIOEvent e) => {
			Debug.Log("商品成功回调:"+e.data);
			lock(goods){
				JSONObject json = new JSONObject (e.data.ToString()) ;
				Main.goods = json["list"].list;
			}

			NotificationCenter.Get().DispatchEvent(API.GOODS,e.data.ToString());
		});
		On("pointgoods-res",(SocketIOEvent e) => {
			Debug.Log("积分成功回调:"+e.data);
			lock(pointGoods){
				pointGoods = new JSONObject (e.data.ToString())["list"].list;
			}
			NotificationCenter.Get().DispatchEvent(API.POINTGOODS,e.data.ToString());
		});

		//支付成功回调
		On("buy-goods-success",(SocketIOEvent e) => {
			Debug.Log("购买商品成功回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.BUYGOODSSUCCESS,e.data.ToString());
		});
		//支付失败回调
		On("buy-goods-error",(SocketIOEvent e) => {
			Debug.Log("购买商品失败回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.BUYGOODSERROR,e.data.ToString());
		});
		//获取牌局统计
		On("room-statistics-res",(SocketIOEvent e) => {
			Debug.Log("分数统计回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.ROOMSTATISTICSRES,e.data.ToString());
		});
		//续费成功
		On("recharge-room-success",(SocketIOEvent e) => {
			Debug.Log("续费成功回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.RECHARGE_SUCCESS,e.data.ToString());
		});

		//获取房费
		On("payprice",(SocketIOEvent e) => {
			Debug.Log("房费回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.PAY_PRICE,e.data.ToString());
		});

		//用户登录成功
		On("user-login-success", (SocketIOEvent e) => {

			Debug.Log("用户登录成功回调:"+e.data);

			JSONObject json = new JSONObject(e.data.ToString());
			PlayerPrefs.SetString("SESSION",json["session"].str);	
			Main.session = json["session"].str;
			#if UNITY_ANDROID || UNITY_IOS
			if(json["fake"] != null && bool.Parse(json["fake"].ToString())){
				//调用微信重新登录
				callWeiXinLogin();
			}
			#endif

			if(queues.Count > 0){
				LoginQueue lq = queues[0];
				lq.isReturn = true;
			}
		});

		//检测是否特殊牌
		On("special-card-list-res",(SocketIOEvent e) => {
			Debug.Log("特殊牌检测回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.CHECK_SPECIAL,e.data.ToString());
		});
		//获取同级总分
		On("room-statistics-res",(SocketIOEvent e) => {
			Debug.Log("获取统计总分回调:"+e.data);
			NotificationCenter.Get().DispatchEvent(API.STASTICS_ROOM,e.data.ToString());
		});
	}
}

public class LoginQueue{
	public string session;
	public string code;
	public bool isReturn;
	public bool isRequest;
	public long time;
}
